const mysql = require('mysql2');

// 创建数据库连接池
const pool = mysql.createPool({
  host: process.env.DB_HOST || 'localhost',
  user: process.env.DB_USER || 'root',
  password: process.env.DB_PASSWORD || 'root',
  database: process.env.DB_NAME || 'admin_manage',
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0,
  // 添加更多连接选项以提高稳定性
  acquireTimeout: 60000,
  timeout: 60000,
  reconnect: true,
  charset: 'utf8mb4',
  collation: 'utf8mb4_unicode_ci'
});

// 获取连接池的Promise版本
const promisePool = pool.promise();

// 测试数据库连接
promisePool.getConnection()
  .then(connection => {
    console.log('数据库连接成功');
    connection.release();
  })
  .catch(err => {
    console.error('数据库连接失败:', err.message);
    console.log('请确保MySQL服务正在运行，并且数据库配置正确');
    console.log('当前配置:');
    console.log('- 主机:', process.env.DB_HOST || 'localhost');
    console.log('- 用户:', process.env.DB_USER || 'root');
    console.log('- 数据库:', process.env.DB_NAME || 'admin_manage');
  });

module.exports = promisePool;